package cn.gson.crm.controller.system;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.gson.crm.interceptor.JsonResult;
import cn.gson.crm.model.dao.ResourcesDao;
import cn.gson.crm.model.entity.Resources;

@Controller
@RequestMapping("/resources/permission")
public class ResourcesController {
	@Autowired
	private ResourcesDao resDao;
	
	
	@RequestMapping("/list")
	@ResponseBody
	public List<Resources> list(){
		return resDao.findAllByParentIsNull();
	}
	
   @RequestMapping({"/form", "/load"})
    public String form(Long id, Model model) {
        if (id != null) {
            //编辑
        	Resources resources = resDao.findOne(id);
            model.addAttribute("resources", resources);
        }
        return "resources/form";
    }

   @PostMapping({"/save", "/update"})
   @ResponseBody
   @Transactional
   public JsonResult form(@Valid Resources permission, BindingResult br) {
       if (!br.hasErrors()) {
    	   resDao.save(permission);
           return JsonResult.success();
       } else {
           return JsonResult.error("校验不通过！");
       }
   }
   
   @PostMapping("/combo")
   @ResponseBody
   public List<Resources> combo() {
       List<Resources> roots = resDao.findAllByParentIsNull();
       return roots;
   }
   @GetMapping("/delete")
   @ResponseBody
   @Transactional
   public JsonResult delete(Long id) {
	   Resources permission = resDao.findOne(id);
       if (permission != null) {
    	   resDao.delete(permission);
           return JsonResult.success();
       }
       return JsonResult.error("数据不存在！");
   }
}
